<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #head {
        display: flex;
        align-items: center;
      }
      #user {
        margin-left: auto;
        border: 2px solid #333;
        background-color: #fff;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        width: 100px;
        height: 100px;
        margin-right: 20px;
        /* text-align: center; */
        display: flex;
        align-items: center;
        justify-content: center;
      }
      #mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.3); 
        z-index: 998; 
        display: none;
      }
      #container {
        width: 300px;
        height: 300px;
        margin: 0 auto;
        border: 2px solid #333;
        background-color: #fff;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        position: fixed; 
        top: 50%; 
        left: 50%; 
        transform: translate(-50%, -50%); 
        z-index: 999; 
        display: none;
      }

      #close {
        position: absolute;
        top: 0;
        right: 10px;
        cursor: pointer;
        font-size: 40px;
      }
      #username {
        position: absolute;
        top: 50%; 
        left: 20px; 
        transform: translateY(-50%); 
        display: inline-flex;
        align-items: center;
      }
      #btn {
        margin-left: 20px;
        font-size: 20px;
      }
      #logout {
        position: absolute;
        bottom: 0;
        right: 20px;
        margin: 10px;
      }
      #wallet {
        width: 300px;
        height: 300px;
        display: flax;
        justify-content: center;
        border: 2px solid #333;
        background-color: #fff;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        position: relative;
      }
      #text {
        font-size: 20px;
        margin: 10px;
      }
      #add,
      #less {
        position: absolute;
        bottom: 10px;
      }
      #add {
        left: 10px;
      }

      #less {
        right: 10px;
      }
      #friends {
        border: 2px solid #333;
        background-color: #fff;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        width: 200px;
        height: 400px;
      }
      #box {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
      }
      #addFriend {
        margin: 10px;
      }
    </style>
  </head>
  <body>
    <div id="head">
      <h1>Hello World</h1>
      <div id="user"></div>
    </div>
    <div id="mask"></div>
    <hr />
    <div id="container">
      <div id="close">X</div>
      <div id="username">
        账户名称：
        <span> </span>
        <div id="btn">
          <button>修改</button>
        </div>
      </div>
      <div id="logout">
        <button>注销</button>
      </div>
    </div>
    <div id="box">
      <div id="wallet">
        <div id="text">钱包</div>
        <div id="balance">
          余额：
          <span></span>
        </div>
        <div id="add">
          <button>增加</button>
        </div>
        <div id="less">
          <button>减少</button>
        </div>
      </div>
      <div id="friends">
        <div id="addFriend">
          <button>添加好友</button>
        </div>
        <hr />
        <div id="friendsList"></div>
      </div>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      const user = document.querySelector("#user");
      const container = document.querySelector("#container");
      const close = document.querySelector("#close");
      const userData = localStorage.getItem("user");
      //点击用户信息
      document.querySelector("#user").innerHTML = userData;
      close.addEventListener("click", (e) => {
        container.style.display = "none";
        document.querySelector("#mask").style.display = "none";
      });
      user.addEventListener("click", (e) => {
        container.style.display = "block";
        document.querySelector("#mask").style.display = "block";
      });
      //获取用户信息
      axios
        .get(`http://305356f7.r28.cpolar.top/users/${userData}`)
        .then((res) => {
          console.log(res);
          let nickname = res.data.nickname;
          document.querySelector("#username span").innerHTML = nickname;
        });
      //修改昵称
      const btn = document.querySelector("#btn button");
      btn.addEventListener("click", (e) => {
        const currentNickname =
          document.querySelector("#username span").innerHTML;
        const newNickname = prompt("请输入新昵称", currentNickname);
        axios
          .put("http://305356f7.r28.cpolar.top/users/nickname", {
            username: userData,
            nickname: newNickname,
          })
          .then((res) => {
            alert("修改成功！");
            document.querySelector("#username span").innerHTML = newNickname;
          });
      });
      //注销
      document.querySelector("#logout").addEventListener("click", () => {
        const isConfirm = confirm("确定要注销账号吗？");
        // 如果用户点击"确定"，执行注销操作
        if (isConfirm) {
          // 发送DELETE请求注销账号
          axios
            .delete(`http://305356f7.r28.cpolar.top/users/${userData}`)
            .then((res) => {
              alert("注销成功！");
              localStorage.removeItem("user");
              window.location.href = "./login.html";
            });
        }
      });
      //钱包
      // 获取余额,立即执行
      (function getBalance() {
        axios
          .get(`http://305356f7.r28.cpolar.top/users/${userData}/balance`)
          .then((res) => {
            let balance = res.data.balance;
            document.querySelector("#balance span").innerHTML = balance;
          });
      })();

      //增加余额
      document.querySelector("#add button").addEventListener("click", () => {
        let num;
        do {
          num = prompt("请输入金额（单位：元）");
          if (num === null) {
            return;
          }
          // 使用正则表达式验证：允许整数或小数（如100或100.5）
          const isValid = /^\d+(\.\d{1,2})?$/.test(num);
          if (!isValid) {
            alert("请输入有效的数字金额！");
          }
        } while (!/^\d+(\.\d{1,2})?$/.test(num));
        axios
          .put(`http://305356f7.r28.cpolar.top/users/${userData}/balance/add`, {
            amount: num,
          })
          .then((res) => {
            alert("余额增加成功！");
            document.querySelector("#balance span").innerHTML =
              res.data.balance;
          });
      });
      //减少余额
      document
        .querySelector("#less button")
        .addEventListener("click", async () => {
          const Balance = await axios.get(
            `http://305356f7.r28.cpolar.top/users/${userData}/balance`
          );
          const currentBalance = Balance.data.balance;
          let num = prompt(`当前还有:${currentBalance}元，请输入扣除金额`);
          do {
            // 验证输入是否为有效数字
            if (!/^\d+(\.\d{1,2})?$/.test(num)) {
              alert("请输入有效的金额！");
              break;
            }
            // 验证金额是否超过余额
            if (parseFloat(num) > currentBalance) {
              alert("余额不足！当前余额: " + currentBalance);
              break;
            }
            break;
          } while (true);
          axios
            .put(
              `http://305356f7.r28.cpolar.top/users/${userData}/balance/deduct`,
              {
                amount: num,
              }
            )
            .then((res) => {
              alert("余额减少成功！");
              document.querySelector("#balance span").innerHTML =
                res.data.balance;
            });
        });

      //添加好友
      function loadFriends() {
        axios
          .get(`http://305356f7.r28.cpolar.top/users/${userData}/friends`)
          .then((res) => {
            console.log(res.data);
            const friendsList = document.querySelector("#friendsList");
            friendsList.innerHTML = ""; // 先清空
            res.data.forEach((friend) => {
              friendsList.innerHTML += `<div>${friend}</div>`;
            });
          });
      }
      document.querySelector("#addFriend").addEventListener("click", () => {
        const friendName = prompt("请输入要添加的好友：").trim();
        axios
          .post(`http://305356f7.r28.cpolar.top/users/${userData}/friend`, {
            friendId: friendName,
          })
          .then((res) => {
            alert(`成功添加${friendName}`);
            loadFriends();
          });
      });
    </script>
  </body>
</html>
